<?php

	/**
	 * @see Bike_Plugin_Abstract
	 */
	require_once 'Bike/Plugin/Abstract.php';
	
	/**
	 * @see Zend_Registry
	 */
	require_once 'Zend/Registry.php';
	
	/**
	 * @see Bike_Model_Mapper_Module
	 */
	require_once 'Bike/Model/Mapper/Module.php';
	
	
	class Bike_Plugin_Modules extends Bike_Plugin_Abstract
    {
        const CONFIG_PLUGIN_NAME = 'modules';

        public function runForCli(Zend_Application $Application)
        {
        	$this->setApplication($Application);
        	$this->routeStartup();
        }

        protected function getModules()
	    {	    	if(!Zend_Registry::isRegistered('modules'))
	    	{	    		$ModuleMapper = Bike_Model_Mapper_Module::getInstance();
        		$Modules = $ModuleMapper->fetchAll();
        		Zend_Registry::set('modules', $Modules);
	    	}

	    	return Zend_Registry::get('modules');
	    }

        public function routeStartup()
        {        	$Modules = $this->getModules();
        	$this->getFrontController()->setModules($this->getModules());
        	$controllerDirectories = array();
        	foreach($Modules as $Module)
        	{        		if($Module->isActive())
        		{
	        		$loader = $Module->setAutoloader();
	        		$this->addResourceTypes($loader);
	        		$Module->addRoutes();
	        		$controllerDirectories[$Module->getModuleName()] = $Module->getControllerDirectory();
				}
        	}
        	$this->getFrontController()->setControllerDirectory($controllerDirectories);
        }

        public function addResourceTypes($Loader)
        {        	$Loader->addResourceTypes(array(
	            'cli' => array(
	                'namespace' => 'Cli',
	                'path'      => 'cli',
	            ),
			));
        }
	}
